global !p

from mdtex.scopes import text
from common.time import get_creation_time, get_modification_time, get_now_time

def front_matter(snip):
    try:
        pre_title = snip.buffer[1][7:]
        pre_date = snip.buffer[2][6:]
    except:
        pre_title = ""
        pre_date = ""
    snip.buffer[0:len(snip.buffer)] = ''
    template = '''---
title: ${{1:{title}}}
date: {date}
updated: {date}
description: $2
draft: {draft}
comments: {comments}
disableNunjucks: true
katex: ${{3|true,false|}}
categories: $4
tags: $5
---
$0'''
    snip.expand_anon(template.format(title    = pre_title, \
                                     date     = pre_date, \
                                     draft    = "true" if ".private" in pre_title else "false", \
                                     comments = "false" if ".private" in pre_title else "true"))

endglobal

context "snip.line == 0 and snip.column == 0"
pre_expand "front_matter(snip)"
snippet @ "Template" A
endsnippet

context "text()"
snippet "date: (.*)" "Date" br
date: `!p snip.rv = get_now_time()`
endsnippet

context "text()"
snippet "updated: (.*)" "Updated" br
updated: `!p snip.rv = get_now_time()`
endsnippet

context "text()"
snippet tag "Tags" w
{% ${1:${VISUAL}} %}$0
endsnippet

context "text() and snip.column == 2"
snippet adm "Admonition"
!!! ${1|note,info,warning,danger,example,quote,tip,memo,test|} ${2:""}
    ${3:${VISUAL}}
$0
endsnippet

context "text() and snip.column == 3"
snippet tabs "Tabs"
{% tabs $1, ${2:-1} %}
${3:${VISUAL}}
{% endtabs %}
$0
endsnippet

context "text() and snip.column == 2"
snippet tab "Tab"
<!-- tab $1 -->
${2:${VISUAL}}
<!-- endtab -->
$0
endsnippet

context "text()"
snippet label "Label" w
{% label ${1|default,primary,success,info,warning,danger|} @${2:${VISUAL}} %}$0
endsnippet

context "text()"
snippet "^categories: (.+)" "Categories Format" ir
`!p
categories = match.group(1).replace("，", ", ").split(",")
format_categories = "categories:"
for category in categories:
    format_categories += "\n  - [" + category.strip() + "]"
snip.rv = format_categories
`
endsnippet

context "text()"
snippet "^tags: ([^[].+)" "Tags Format" ir
tags: [`!p snip.rv = match.group(1).replace(",", ", ").replace("，", ", ")`]
endsnippet

context "text()"
snippet "^tags: \[(.+)\]([^[\]]+)" "Tags Format" ir
tags: [`!p snip.rv = match.group(1) + ", " + match.group(2).replace(",", ", ").replace("，", ", ")`]
endsnippet
